package im.elephas.androfan.activity;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import im.elephas.androfan.R;
import im.elephas.androfan.fanfouapi.FanfouApi;
import im.elephas.androfan.fanfouapi.events.IErrorEvent;
import im.elephas.androfan.fanfouapi.events.IUpdateEvent;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class SendMessageActivity extends AndroFanActivity implements
		OnClickListener, TextWatcher {

	private String atName = "";
	private String replyId = "";
	private boolean isReply = false;

	private ImageButton messageButton;
	private ImageButton pictureButton;
	private EditText et;
	private TextView tv;

	private Uri pictureUri;
	private Boolean isSendPicture = false;

	private String msg;

	private IErrorEvent mIErrorEvent = new IErrorEvent() {

		@Override
		public void errorHandler() {
			Builder dialog = new AlertDialog.Builder(getActivity());
			dialog.setTitle("获取消息失败！请检查网络设置。");
			dialog.show();
			getActivity().finish();
		}
	};
	private IUpdateEvent mIUpdateEvent = new IUpdateEvent() {

		@Override
		public void updateHandler(String result) {
			getActivity().finish();
		}
	};

	@Override
	public void afterTextChanged(Editable s) {
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode != RESULT_OK) {
			return;
		}
		
		messageButton.setEnabled(true);
		
		if (requestCode == 0) {
			pictureUri = intent.getData();
			isSendPicture = true;
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(messageButton)) {
			String status = et.getText().toString();
			if (isReply) {
				getFanfouApi().replyMessage(status, replyId, mIUpdateEvent,
						mIErrorEvent);
			} else if (isSendPicture) {
				// TODO
				try {
					ContentResolver cr = getContentResolver();
					InputStream is = cr.openInputStream(pictureUri);
					File file = new File(
							"/data/data/im.elephas.androfan/sendpic.jpg");
					file.createNewFile();
					FileOutputStream fos = new FileOutputStream(file);
					byte[] buf = new byte[2048];

					int num = is.read(buf);
					while (num != -1) {
						fos.write(buf, 0, num);
						fos.flush();
						num = is.read(buf);
					}
					is.close();
					fos.close();
					getFanfouApi().updateMessageWithPhoto(status, file,
							mIUpdateEvent, mIErrorEvent);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				getFanfouApi().updateMessage(status, mIUpdateEvent,
						mIErrorEvent);
			}
			et.setEnabled(false);
			messageButton.setEnabled(false);
		}
		if (v.equals(pictureButton)) {
			Builder dialog = new AlertDialog.Builder(getActivity());
			dialog.setTitle("请选择照片获取方式");
			String[] sel = { "选择一张照片", "直接照相上传" };
			dialog.setItems(sel, new Dialog.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					Intent i;
					switch (arg1) {
					case 0:
						i = new Intent(Intent.ACTION_GET_CONTENT);
						i.setType("image/*");
						i.putExtra("return-data", true);
						startActivityForResult(i, 0);
						break;
					case 1:
						i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(i, 1);
						break;
					default:
						break;
					}
				}
			});
			dialog.show();
		}
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		int i = et.getText().length();
		if (i <= 140 && i >= 0) {
			messageButton.setEnabled(true);
			tv.setText(Integer.toString(140 - i));
		} else {
			messageButton.setEnabled(false);
			et.setText(msg);
		}
		msg = new String(et.getText().toString());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newmessage);
		setTitle("你在做什么？");

		try {
			isReply = getIntent().getExtras().getBoolean("isreply");
		} catch (Exception e) {
			isReply = false;
		}

		et = (EditText) findViewById(R.id.messageEditText);
		messageButton = (ImageButton) findViewById(R.id.sendButton);
		messageButton.setOnClickListener(this);
		messageButton.setEnabled(false);
		pictureButton = (ImageButton) findViewById(R.id.pictureButton);
		pictureButton.setOnClickListener(this);
		pictureButton.setEnabled(true);

		if (isReply) {
			atName = getIntent().getExtras().getString("atname");
			replyId = getIntent().getExtras().getString("replyid");
			setTitle("回复@" + atName);
			et.setText("@" + atName + " ");

			pictureButton.setVisibility(View.GONE);
		}
		et.addTextChangedListener(this);

		tv = (TextView) findViewById(R.id.countTextView);
		int i = et.getText().length();
		tv.setText(Integer.toString(140 - i));
	}

}
